<script setup>
import { ref, onMounted } from 'vue'

const isLoggedIn = ref(false)
const userInfo = ref(null)
const hasUnreadNotifications = ref(false)
const membershipLevel = ref('free')

onMounted(() => {
  checkLoginStatus()
  checkUnreadNotifications()
  // 登录状态检查已在checkLoginStatus中完成，这里不需要重复获取userInfo
})

// 检查是否有未读消息
function checkUnreadNotifications() {
  try {
    const savedNotifications = uni.getStorageSync('notifications')
    if (savedNotifications) {
      const notifications = JSON.parse(savedNotifications)
      hasUnreadNotifications.value = notifications.some(item => !item.read)
    }
  } catch (e) {
    console.error('检查未读消息失败', e)
  }
}

function checkLoginStatus() {
  try {
    const loginStatus = uni.getStorageSync('isLoggedIn')
    if (loginStatus) {
      isLoggedIn.value = true
      const storedUserInfo = uni.getStorageSync('userInfo')
      if (storedUserInfo) {
        userInfo.value = storedUserInfo
        membershipLevel.value = storedUserInfo.membershipLevel || 'free'
      }
    } else {
      isLoggedIn.value = false
      userInfo.value = null
    }
  } catch (e) {
    console.error('获取登录状态失败', e)
  }
}

function handleLogout() {
  uni.showModal({
    title: '提示',
    content: '确定要退出登录吗？',
    success: (res) => {
      if (res.confirm) {
        // 清除登录状态
        uni.removeStorageSync('isLoggedIn')
        uni.removeStorageSync('userInfo')
        isLoggedIn.value = false
        userInfo.value = null
        
        // 立即跳转到登录选择页
        uni.reLaunch({
          url: '/pages/index',
          success: function() {
            console.log('退出登录后返回到登录选择页成功')
          },
          fail: function(err) {
            console.error('退出登录后返回到登录选择页失败', err)
          }
        })
      }
    }
  })
}

function goToLogin() {
  uni.navigateTo({
    url: '/pages/login/index'
  })
}

function navigateTo(url) {
  // 判断是否为tabBar页面，如果是则使用switchTab
  const tabBarPages = [
    '/pages/home/index', 
    '/pages/mine/index'
  ];
  
  if (tabBarPages.includes(url)) {
    uni.switchTab({
      url: url
    });
  } else {
    uni.navigateTo({
      url: url
    });
  }
}

function goToHealthRecords() {
  uni.navigateTo({
    url: '/pages/mine/health-records'
  })
}

// 联系客服
function contactCustomerService() {
  uni.showModal({
    title: '联系客服',
    content: '请选择联系方式',
    showCancel: true,
    cancelText: '取消',
    confirmText: '在线咨询',
    success: (res) => {
      if (res.confirm) {
        // 打开在线客服聊天窗口
        uni.openCustomerServiceChat({
          extInfo: { url: 'https://work.weixin.qq.com/kfid/your_kfid' },
          corpId: 'your_corpId',
          success(res) {
            console.log('打开客服聊天窗口成功')
          },
          fail(err) {
            console.error('打开客服聊天窗口失败：', err)
            // 如果打开失败，显示客服电话
            uni.makePhoneCall({
              phoneNumber: '400-123-4567'
            })
          }
        })
      }
    }
  })
}

// 跳转到会员页面
function goToMembership() {
  uni.navigateTo({
    url: '/pages/mine/membership'
  })
}

// 跳转到设置页面
function goToSettings() {
  uni.navigateTo({
    url: '/pages/mine/settings'
  })
}
</script>

<template>
  <view class="container">
    <view class="header">
      <view class="title">我的</view>
    </view>
    
    <view v-if="isLoggedIn" class="user-info">
      <view class="avatar">
        <image :src="userInfo?.avatar || '/static/logo.png'" mode="aspectFill" />
      </view>
      <view class="info">
        <view class="nickname">{{ userInfo?.nickname || userInfo?.username || '未登录' }}</view>
        <view class="membership" @click="goToMembership">
          <text class="level">{{ membershipLevel === 'premium' ? 'VIP会员' : '免费会员' }}</text>
          <text class="iconfont icon-right"></text>
        </view>
      </view>
    </view>
    
    <view v-else class="not-logged-in">
      <view class="login-tip">您还未登录</view>
      <button class="login-btn" @click="goToLogin">去登录</button>
    </view>
    
    <view class="user-status" v-if="isLoggedIn">
      <view class="membership-level">
        <text class="level-label">会员等级:</text>
        <text class="level-value" :class="{'premium-level': membershipLevel === 'premium'}">
          {{ membershipLevel === 'premium' ? '高级会员' : '免费会员' }}
        </text>
      </view>
      <view class="account-type" v-if="userInfo">
        <text class="type-label">账号类型:</text>
        <text class="type-value">{{ userInfo.accountType === 'family' ? '家庭账号' : (userInfo.accountType === 'admin' ? '管理员账号' : '个人账号') }}</text>
      </view>
    </view>
    
    <view class="menu-list">
      <view class="menu-item" @tap="navigateTo('/pages/basic-info/index')">
        <text class="menu-title">个人资料</text>
        <text class="menu-arrow">></text>
      </view>
      
      <view class="menu-item" @tap="goToHealthRecords">
        <text class="menu-title">健康档案</text>
        <text class="menu-arrow">></text>
      </view>
      
      <view v-if="isLoggedIn && userInfo?.accountType === 'family'" class="menu-item" @tap="navigateTo('/pages/mine/family-members')">
        <text class="menu-title">家庭成员管理</text>
        <text class="menu-badge">{{ userInfo?.currentMembers || 0 }}/{{ userInfo?.maxMembers || 3 }}</text>
        <text class="menu-arrow">></text>
      </view>
      
      <view class="menu-item" @tap="navigateTo('/pages/mine/membership')">
        <text class="menu-title">会员权限服务</text>
        <text v-if="userInfo?.membershipLevel !== 'premium'" class="menu-tag">升级</text>
        <text class="menu-arrow">></text>
      </view>
      
      <view class="menu-item" @tap="navigateTo('/pages/mine/notifications')">
        <text class="menu-title">消息通知</text>
        <text v-if="hasUnreadNotifications" class="menu-badge notification-badge">新</text>
        <text class="menu-arrow">></text>
      </view>

      <view class="menu-item" @tap="contactCustomerService">
        <text class="menu-title">在线客服</text>
        <text class="menu-arrow">></text>
      </view>
      
      <view class="menu-item" @tap="navigateTo('/pages/mine/settings')">
        <text class="menu-title">设置</text>
        <text class="menu-arrow">></text>
      </view>
    </view>
    
    <view v-if="isLoggedIn" class="logout-btn" @click="handleLogout">
      退出登录
    </view>
  </view>
</template>

<style lang="scss" scoped>
.container
{
    min-height: 100vh;
    padding: 30rpx;
    background-color: #f5f5f5;
}

.header
{
    margin-bottom: 40rpx;

    .title
    {
        font-size: 40rpx;
        font-weight: bold;

        color: #333;
    }
}

.user-info
{
    display: flex;
    align-items: center;

    margin-bottom: 30rpx;
    padding: 30rpx;

    border-radius: 12rpx;
    background-color: #fff;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, .05);

    .avatar
    {
        overflow: hidden;

        width: 120rpx;
        height: 120rpx;
        margin-right: 30rpx;

        border-radius: 60rpx;

        image
        {
            width: 100%;
            height: 100%;
        }
    }

    .info
    {
        flex: 1;

        .nickname
        {
            font-size: 36rpx;
            font-weight: bold;

            margin-bottom: 10rpx;

            color: #333;
        }

        .membership
        {
            display: flex;
            align-items: center;
            
            .level
            {
                font-size: 28rpx;
                color: #1890ff;
                margin-right: 10rpx;
            }
            
            .icon-right
            {
                font-size: 24rpx;
                color: #999;
            }
        }
    }
}

.not-logged-in
{
    display: flex;
    align-items: center;
    flex-direction: column;

    margin-bottom: 30rpx;
    padding: 40rpx;

    border-radius: 12rpx;
    background-color: #fff;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, .05);

    .login-tip
    {
        font-size: 30rpx;

        margin-bottom: 30rpx;

        color: #666;
    }

    .login-btn
    {
        font-size: 28rpx;

        display: flex;
        align-items: center;
        justify-content: center;

        width: 200rpx;
        height: 70rpx;

        color: #fff;
        border-radius: 35rpx;
        background-color: #1890ff;
    }
}

.user-status
{
    display: flex;
    justify-content: space-between;

    margin-bottom: 30rpx;
    padding: 20rpx 30rpx;

    border-radius: 12rpx;
    background-color: #fff;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, .05);

    .membership-level,
    .account-type
    {
        display: flex;
        align-items: center;
    }

    .level-label,
    .type-label
    {
        font-size: 26rpx;

        margin-right: 10rpx;

        color: #666;
    }

    .level-value,
    .type-value
    {
        font-size: 26rpx;
        font-weight: 500;

        color: #333;
    }

    .premium-level
    {
        color: #ff9c00;
    }
}

.logout-btn
{
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    background-color: #fff;
    border-radius: 12rpx;
    text-align: center;
    font-size: 30rpx;
    color: #ff4d4f;
    margin-top: 40rpx;
}

.menu-list
{
    background-color: #fff;
    border-radius: 12rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

    .menu-item
    {
        display: flex;
        align-items: center;
        justify-content: space-between;

        padding: 30rpx;

        transition: all .3s ease;

        border-bottom: 1px solid #f0f0f0;

        &:active
        {
            background-color: #f9f9f9;
        }

        &:last-child
        {
            border-bottom: none;
        }

        .menu-title
        {
            font-size: 28rpx;

            display: flex;
            align-items: center;

            color: #333;

            &::before
            {
                width: 8rpx;
                height: 8rpx;
                margin-right: 15rpx;

                content: '';

                border-radius: 50%;
                background-color: #1890ff;
            }
        }

        .menu-arrow
        {
            font-family: 'Arial';
            font-size: 28rpx;
            font-weight: 300;

            transform: scale(1.2);

            color: #999;
        }

        .menu-badge
        {
            font-size: 24rpx;

            margin-right: 10rpx;
            padding: 4rpx 12rpx;

            color: #666;
            border-radius: 25rpx;
            background-color: #f0f0f0;
        }
        
        .notification-badge
        {
            color: #fff;
            background-color: #ff4d4f;
        }

        .menu-tag
        {
            font-size: 22rpx;

            margin-right: 10rpx;
            padding: 4rpx 12rpx;

            color: #fff;
            border-radius: 25rpx;
            background-color: #ff9c00;
        }
    }
}
</style>